import re

from django.contrib.auth import get_user_model, authenticate
from django.core.validators import FileExtensionValidator
from django.template.context_processors import request
from rest_framework import serializers
from django.contrib.auth import get_user_model
from apps.oaauth.models import OAUser

OAUser = get_user_model()
class AddStaffSerializer(serializers.Serializer):
    realname = serializers.CharField(required=True, max_length=20, error_messages={
        'required':"请输入真实姓名",
        'max_length':"员工姓名超长",
    })
    email = serializers.CharField(required=True, max_length=50, error_messages={
        'required':'请输入邮箱！'
    })
    password = serializers.CharField(required=True, max_length=50, error_messages={
        'required':'请输入密码！'
    })
    telephone = serializers.IntegerField(required=True, error_messages={
        'required':'请输入手机号！'
    })
    def validate_telephone(self, value):
        pattern = r'^1[3-9]\d{9}$'
        if not re.match(pattern, str(value)):
            raise serializers.ValidationError("手机号格式不符")

    def validate(self, attrs):
        request = self.context.get('request')
        email = attrs.get('email')
        if OAUser.objects.filter(email=email).exists():
            raise serializers.ValidationError("邮箱已存在！")
        if request.user.department.leader.uid != request.user.uid:
            raise serializers.ValidationError("你不是部门领导！")
        attrs['telephone'] = request.data.get('telephone')
        return attrs

class ActiveStaffSerializer(serializers.Serializer):
    email = serializers.CharField(required=True, max_length=50, error_messages={
        'required': '请输入邮箱！'
    })
    password = serializers.CharField(required=True, max_length=50, error_messages={
        'required': '请输入密码！'
    })
    def validate(self, attrs):
        email = attrs.get('email')
        password = attrs.get('password')
        user = OAUser.objects.filter(email=email).first()
        if not user or not user.check_password(password):
            raise serializers.ValidationError("邮箱或密码错误！")
        attrs['user'] = user
        return attrs

    def to_representation(self, instance):
        # 重写 to_representation 方法以包含用户对象
        ret = super().to_representation(instance)
        # 假设您想要返回用户的一些额外信息，例如用户名
        ret['user'] = instance['user']
        return ret

class StaffUploadSerializer(serializers.Serializer):
    file = serializers.FileField(
        validators=[FileExtensionValidator(allowed_extensions=['xlsx', 'xls', 'csv'])]
        ,required=True
    )
